import { awaitWrap, limitStr } from '@src/assets/js/tool'
import style from './index.module.less'
import PageComponent from '@components/pageComponent'
import { FolderOutline } from 'antd-mobile-icons'
import { Button, Toast } from 'antd-mobile'
import MessageList from './components/messageList'
import { useRef, useState } from 'react'
import { addFriendRequest, sendMessageRequest, readRequest } from './ajax'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { setList, setLoadMoreVersion, setVersion } from '@src/redux/reducers/chart'
import { requestOneFile } from '@src/assets/js/request'
import { pop } from '@src/redux/reducers/pages'

async function readMessage (caseid, id, callback) {
  await awaitWrap(readRequest(caseid, id))
  callback()
}

async function addFriend (
  currentCase,
  person,
  mine
) {
  await awaitWrap(addFriendRequest(currentCase.id, person.accountid, mine.action_subject, person.action_subject))
}

async function sendMessage (currentCase, person, callback, content, fileid, dispatch) {
  const [e] = await awaitWrap(sendMessageRequest(currentCase.id, person.accountid, person.name, content, fileid))
  if (e === null) {
    dispatch(setLoadMoreVersion(Date.now()))
    await awaitWrap(readMessage(currentCase.id, person.accountid, callback))
  }
}

async function sendHandle (text, currentCase, person, mine, setLoading, dispatch, callback) {
  if (text === '') {
    Toast.show({ content: '消息不能为空' })
    return undefined
  }
  if (currentCase === null || person === null || mine === null) {
    return undefined
  }
  if (person.accountid === null || person.accountid === undefined || (typeof person.accountid === 'string' && person.accountid === '')) {
    Toast.show({ content: `${person.name}账号不存在` })
    return undefined
  }
  setLoading(true)
  if (person.isfriend === 0) {
    const [e] = await awaitWrap(addFriend(currentCase, person, mine))
    if (e !== null) {
      setLoading(false)
      return undefined
    }
  }
  await awaitWrap(sendMessage(currentCase, person, () => { setLoading(false); callback() }, text, '', dispatch))
}

async function uploadHandle (
  f,
  currentCase,
  person,
  mine,
  inputRef,
  dispatch,
  refreshFn,
  setLoading
) {
  if (f === null) {
    return undefined
  }
  if (currentCase === null || person === null || mine === null) {
    return undefined
  }
  let fileid = ''
  setLoading(true)
  if (f !== undefined) {
    Toast.show({
      content: '上传中',
      icon: 'loading',
      duration: 0
    })
    const [err, res] = await awaitWrap(requestOneFile(f))
    Toast.clear()
    if (err === null && res !== null) {
      fileid = res.id
    }
  }
  if (inputRef.current !== null) {
    inputRef.current.value = ''
  }
  await awaitWrap(sendMessage(currentCase, person, () => { refreshFn() }, '', fileid, dispatch))
  setLoading(false)
}

function Main ({ title }) {
  const dispatch = useAppDispatch()
  const inputRef = useRef(null)
  const [text, setText] = useState('')
  const currentCase = useAppSelector(state => state.chart.currentCase)
  const currentPerson = useAppSelector(state => state.chart.currentPerson)
  const mine = useAppSelector(state => state.chart.mine)
  const [loading, setLoading] = useState(false)
  const cases = useAppSelector(state => state.chart.list)
  return (
    <PageComponent title={limitStr(title, 10)} onBack={() => {
      readMessage(currentCase.id, currentPerson.accountid, () => {
        dispatch(setVersion(Date.now()))
        const o = cases.find(li => li.id === currentCase.id)
        if (o) {
          o.c = 0
        }
        dispatch(setList(cases))
      })
      dispatch(pop())
    }}>
      <div className={style.container}>
        <div className={style.content}>
          <div className={style.inner}>
            <MessageList />
          </div>
        </div>
        <div className={style.operate}>
          <label className={style.file}>
            <input ref={inputRef} type='file' onChange={e => {
              const f = e.target.files !== null ? e.target.files[0] : null
              if (f !== null) {
                uploadHandle(f, currentCase, currentPerson, mine, inputRef, dispatch, () => { dispatch(setVersion(Date.now())) }, setLoading).then(null, null)
              }
            }} />
            <div className={style['file-icon']}>
              <FolderOutline />
            </div>
          </label>
          <input placeholder='请输入' className={style.input} value={text} onInput={e => setText(e.target.value)} />
          <Button size='small' color='primary' loading={loading} onClick={() => {
            sendHandle(text, currentCase, currentPerson, mine, setLoading, dispatch, () => { setText(''); dispatch(setVersion(Date.now())); })
          }}>发送</Button>
        </div>
      </div>
    </PageComponent>
  )
}

export default Main
